use super::solution::Solution;


impl Solution {
    pub fn fraction_addition(mut expression: String) -> String {
        if !expression.starts_with("-"){
            expression="+".to_string()+&expression;
        }
        let  expression=expression.as_bytes();
        let mut ans =String::new();
        let a=expression.chunk_by(|_a,&b|b!=b'-'&&b!=b'+').fold((0,1), |mut c,mut cur|{
            let  op=cur[0];
            cur=&cur[1..];
            let t =String::from_utf8(cur.to_vec()).unwrap();
            let nums:Vec<&str>=t.split("/").collect();
            let mut n:(i32,i32) =(nums[0].parse().unwrap(),nums[1].parse().unwrap());
            if op==b'-'{
                n.0*=-1
            }
            if c.1!=n.1{
                n.0*=c.1;
                c.0*=n.1;
                c.1*=n.1;
                
            }
            c.0+=n.0;
            c
        });
        let mut  appro;
        let (mut a1,mut b1)=(a.0.abs(),a.1.abs());
        while a1%b1!=0{
            appro=a1%b1;
            a1=b1;
            b1=appro;
        }
        if a.0|(a.1)<0{
            ans+="-";
        }
        ans+=&(a.0/b1).abs().to_string();
        ans+="/";
        if (a.1/b1)==0{
            ans+="1";
        }else{
            ans+=&(a.1/b1).abs().to_string();
        }
        ans
    }
}


#[cfg(test)]
mod test{
    use super::Solution;
    #[test]
    pub fn test_fraction_addition(){
        Solution::fraction_addition("4/1+6/5-1/8-9/2-1/1+6/7-10/7-3/4-3/2-1/1".to_string());
    }
}